﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InfoService.Utils;
using MediaPortal.Player;
using MediaPortal.GUI.Library;

namespace InfoService.Twitter
{
    public static class TwitterUpdater
    {
        private static readonly Logger logger = Logger.GetInstance();
        public static void SetupUpdater()
        {
            UpdateTimer.OnTimeForUpdateProperties += new UpdateTimer.UpdatePropertiesHandler(UpdateTimer_UpdateProperties);
            g_Player.PlayBackStarted += new g_Player.StartedHandler(g_Player_PlayBackStarted);
        }
        static void g_Player_PlayBackStarted(g_Player.MediaType type, string filename)
        {
            if (type == g_Player.MediaType.Video && TwitterService.PostWatchingVideos)
            {
                logger.WriteLog("Try to post tweet for video " + filename, LogLevel.Debug, InfoServiceModul.Twitter);
                string title = string.Empty;
                string curId = GUIPropertyManager.GetProperty("#currentmoduleid");
                if (curId == "96742" && TwitterService.PostUsingMovingPictures) title = GUIPropertyManager.GetProperty("#MovingPictures.SelectedMovie.title");
                else if (curId == "9811" && TwitterService.PostUsingTVSeries) title = GUIPropertyManager.GetProperty("#TVSeries.Title");
                else if (curId == "6" && TwitterService.PostUsingMyVideos) title = GUIPropertyManager.GetProperty("#Play.Current.Title");
                if (!string.IsNullOrEmpty(title))
                {
                    if (TwitterService.Enabled)
                    {
                        string postText = TwitterService.PostWatchMask;
                        postText = postText.Replace("%video%", title);
                        postText = postText.Replace("%filename%", System.IO.Path.GetFileNameWithoutExtension(filename));
                        postText = postText.Replace("%ext%", System.IO.Path.GetExtension(filename));
                        TwitterService.PostStatus(postText);
                    }
                }
            }
        }

        static void UpdateTimer_UpdateProperties()
        {
            if (TwitterService.Enabled)
            {
                if (!TwitterService.UpdateOnStartup)
                {
                    TwitterService.LastRefresh = DateTime.Now;
                    TwitterService.UpdateOnStartup = true;
                }
                TimeSpan spanTwitter = DateTime.Now - TwitterService.LastRefresh;
                if (((int)spanTwitter.TotalMinutes) >= TwitterService.RefreshInterval)
                {
                    TwitterUtils.UpdateTwitterDataAsync();
                }
            }
        }
    }
}
